package com.region.spring.cloud.config;

import com.region.common.adapter.logging.LoggerAdapter;
import com.region.common.adapter.logging.LoggerAdapterFactory;
import com.region.http.client.core.RegionClientFactory;
import com.region.spring.RegionClientFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Set;

/**
 * @author 26225
 * @date 2024/8/3 17:14
 * @description
 */
@ConditionalOnBean(value = {RegionClientFactoryBean.class})
@Configuration
public class RegionConfigRefresher implements InitializingBean, EnvironmentAware, ApplicationContextAware, ApplicationListener<EnvironmentChangeEvent> {

    private static final LoggerAdapter loggerAdapter = LoggerAdapterFactory.getLogger(RegionConfigRefresher.class);

    private final String FACTORY_BEAN_NAME = "region.client.cloud.reference.name";

    private Environment environment;

    private ApplicationContext context;

    private RegionClientFactoryBean regionClientFactoryBean;

    private RegionClientFactory factory;

    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        if (factory == null) {
            afterPropertiesSet();
        }
        Set<String> keys = event.getKeys();
        for (String changeKey : keys) {
            String value = environment.getProperty(changeKey);
            loggerAdapter.info("The change key is [" + changeKey + "] and change value is [" + value + "]");
            factory.refreshEnv(changeKey, value);
        }
    }

    @Override
    public void afterPropertiesSet() {
        if (factory == null) {
            String value = environment.getProperty(FACTORY_BEAN_NAME);
            regionClientFactoryBean = value == null ? context.getBean(RegionClientFactoryBean.class) : context.getBean(value, RegionClientFactoryBean.class);
            factory = regionClientFactoryBean.getFactory();
        }
        loggerAdapter.info("Initializing RegionConfigRefresher bean. factory bean is " + factory);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
